package main

import (
	"fmt"
	"math/rand"
	"os"
	"time"
)

// 测试数据生成器
type TestDataGenerator struct {
	Cities      []string
	Subjects    []string
	Grades      []string
	MaleNames   []string
	FemaleNames []string
	Surnames    []string
	Statuses    []string
	Notes       []string
}

// Customer 客户结构
type Customer struct {
	Name    string
	Phone   string
	Age     int
	Gender  string
	City    string
	Subject string
	Grade   string
	Notes   string
	Status  string
}

func NewTestDataGenerator() *TestDataGenerator {
	return &TestDataGenerator{
		Cities: []string{
			"北京", "上海", "广州", "深圳", "杭州",
			"南京", "成都", "武汉", "西安", "重庆",
			"天津", "苏州", "长沙", "郑州", "青岛",
		},
		Subjects: []string{
			"数学", "英语", "语文", "物理", "化学",
			"生物", "历史", "地理", "政治",
		},
		Grades: []string{
			"初一", "初二", "初三", "高一", "高二", "高三",
		},
		MaleNames: []string{
			"小明", "小强", "小华", "小军", "小龙", "小峰", "小伟", "小杰",
			"小涛", "小磊", "小亮", "小刚", "小斌", "小超", "小勇", "小东",
			"小波", "小虎", "小辉", "小鹏", "小健", "小飞", "小凯", "小宇",
		},
		FemaleNames: []string{
			"小红", "小美", "小丽", "小芳", "小燕", "小花", "小娟", "小霞",
			"小玲", "小慧", "小静", "小雨", "小梅", "小兰", "小凤", "小敏",
			"小艳", "小娜", "小莉", "小琴", "小丹", "小芬", "小萍", "小云",
		},
		Surnames: []string{
			"张", "李", "王", "赵", "刘", "陈", "周", "吴", "郑", "孙",
			"马", "林", "黄", "许", "谢", "何", "罗", "梁", "邓", "冯",
			"蒋", "沈", "韩", "曹", "彭", "董", "高", "袁", "薛", "范",
			"汤", "尹", "卢", "钟", "石", "龚", "崔", "毛", "段", "邱",
		},
		Statuses: []string{"new", "contacted", "interested", "enrolled", "invalid"},
		Notes: []string{
			"数学基础较好，希望提高解题技巧",
			"英语口语需要加强，准备中考",
			"物理概念理解有困难",
			"作文写作能力需要提升",
			"准备高考，化学是弱项",
			"数学成绩中等，想要提高到优秀",
			"英语语法掌握不好",
			"物理实验操作需要指导",
			"阅读理解能力较弱",
			"生物知识点记忆困难",
			"对数学很感兴趣，希望参加竞赛",
			"英语听力需要加强训练",
			"化学实验很感兴趣",
			"古诗词背诵有困难",
			"物理计算题经常出错",
			"数学逻辑思维需要培养",
			"英语单词记忆困难",
			"生物图表分析能力弱",
			"语文基础知识掌握不牢",
			"化学方程式配平有问题",
		},
	}
}

func (g *TestDataGenerator) GenerateCustomer(id int) Customer {
	rand.Seed(time.Now().UnixNano() + int64(id))

	// 随机选择性别
	gender := "male"
	if rand.Intn(2) == 0 {
		gender = "female"
	}

	// 根据性别选择名字
	var firstName string
	if gender == "male" {
		firstName = g.MaleNames[rand.Intn(len(g.MaleNames))]
	} else {
		firstName = g.FemaleNames[rand.Intn(len(g.FemaleNames))]
	}

	// 生成完整姓名
	surname := g.Surnames[rand.Intn(len(g.Surnames))]
	name := surname + firstName

	// 生成手机号（以138开头的测试号码）
	phone := fmt.Sprintf("138%04d%04d", rand.Intn(10000), rand.Intn(10000))

	// 根据年级生成合理年龄
	grade := g.Grades[rand.Intn(len(g.Grades))]
	var age int
	switch grade {
	case "初一":
		age = 12 + rand.Intn(2) // 12-13岁
	case "初二":
		age = 13 + rand.Intn(2) // 13-14岁
	case "初三":
		age = 14 + rand.Intn(2) // 14-15岁
	case "高一":
		age = 15 + rand.Intn(2) // 15-16岁
	case "高二":
		age = 16 + rand.Intn(2) // 16-17岁
	case "高三":
		age = 17 + rand.Intn(2) // 17-18岁
	}

	return Customer{
		Name:    name,
		Phone:   phone,
		Age:     age,
		Gender:  gender,
		City:    g.Cities[rand.Intn(len(g.Cities))],
		Subject: g.Subjects[rand.Intn(len(g.Subjects))],
		Grade:   grade,
		Notes:   g.Notes[rand.Intn(len(g.Notes))],
		Status:  g.Statuses[rand.Intn(len(g.Statuses))],
	}
}

func (g *TestDataGenerator) GenerateSQL(count int) string {
	sql := "-- 随机生成的客户测试数据\n"
	sql += "-- 生成时间: " + time.Now().Format("2006-01-02 15:04:05") + "\n\n"
	sql += "SET FOREIGN_KEY_CHECKS = 0;\n\n"
	sql += "INSERT INTO `customers` (`name`, `phone`, `age`, `gender`, `city`, `subject`, `grade`, `notes`, `status`, `created_by`, `created_at`, `updated_at`) VALUES\n"

	for i := 0; i < count; i++ {
		customer := g.GenerateCustomer(i)
		sql += fmt.Sprintf("('%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', 1, NOW(), NOW())",
			customer.Name,
			customer.Phone,
			customer.Age,
			customer.Gender,
			customer.City,
			customer.Subject,
			customer.Grade,
			customer.Notes,
			customer.Status,
		)

		if i < count-1 {
			sql += ",\n"
		} else {
			sql += ";\n\n"
		}
	}

	sql += "SET FOREIGN_KEY_CHECKS = 1;\n\n"
	sql += "-- 数据生成完成\n"
	sql += "SELECT '随机客户数据生成完成！' AS message;\n"
	sql += "SELECT COUNT(*) AS total_customers FROM customers;\n"

	return sql
}

func main() {
	if len(os.Args) < 2 {
		fmt.Println("使用方法: go run generate_test_data.go <客户数量> [输出文件]")
		fmt.Println("示例: go run generate_test_data.go 100")
		fmt.Println("示例: go run generate_test_data.go 100 random_customers.sql")
		os.Exit(1)
	}

	var count int
	if _, err := fmt.Sscanf(os.Args[1], "%d", &count); err != nil {
		fmt.Printf("错误: 无效的客户数量 '%s'\n", os.Args[1])
		os.Exit(1)
	}

	if count <= 0 || count > 10000 {
		fmt.Println("错误: 客户数量必须在 1-10000 之间")
		os.Exit(1)
	}

	generator := NewTestDataGenerator()
	sql := generator.GenerateSQL(count)

	// 确定输出文件名
	filename := "random_customers.sql"
	if len(os.Args) >= 3 {
		filename = os.Args[2]
	}

	// 写入文件
	if err := os.WriteFile(filename, []byte(sql), 0644); err != nil {
		fmt.Printf("错误: 无法写入文件 '%s': %v\n", filename, err)
		os.Exit(1)
	}

	fmt.Printf("✅ 成功生成 %d 个客户的测试数据\n", count)
	fmt.Printf("📁 输出文件: %s\n", filename)
	fmt.Printf("💡 导入命令: mysql -u root -p simple_crm < %s\n", filename)
}
